#include <stdio.h>
#include <string.h>

void  removeExtraSapce(char * str)
{
    int pos = 0;
    /*字符串的长度*/
    int length = strlen(str);
    /*1.找到第一个不为空格的位置*/
    int idx = 0;
    while (str[idx] == ' ')
    {
        idx++;
    }
    /*什么时候退出循环？第一个不为空格的位置.*/

    for(;idx < length;idx++)
    {
        if(str[idx] != ' ')
        {
            str[pos] = str[idx];
            pos++;
        }
        else 
        {if(str[idx+1] != ' '&&str[idx+1]!='\0')
        {
            str[pos] = ' ';
            pos++;
        }
        } 
    }
    str[pos] ='\0';
    
}

void  reverseStr(char * str,int left,int right)
{
    right--;
    while (left<right)
    {
        char tmp = str[left];
        str[left] = str[right];
        str[right] = tmp;

        left++;
        right--;
    }
}

void  reverseWord(char * str)
{
    int length = strlen(str);
    int start = 0;
    int end = 0;
    for(int idx = 0;idx < length;idx++)
    {
        if(str[idx] == ' ')
        {
        end = idx;
        reverseStr(str,start,end);
        start = end+1;
        }
    }
    reverseStr(str,start,length);

}


int main()
{
    char buffer[] = "     welcome   to  jiangshu nanjing       ";
        
    
        /*第一步：去掉多余空格*/

        removeExtraSapce(buffer);
        printf("%s\n",buffer); 

        
        /*第二步：将整个字符串逆序*/
        int length = strlen(buffer);
        reverseStr(buffer,0,length);
        printf("%s\n",buffer); 

        /*第三步：将每个字母逆序*/
        reverseWord(buffer);
        printf("%s\n",buffer); 



    
    

}
